package com.feiyisys.controller;

import com.feiyisys.entity.Notice;
import com.feiyisys.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    private NoticeService noticeService;


    @GetMapping("/list")
    public Map<String, Object> listNotices(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {

        // 获取分页数据
        List<Notice> notices = noticeService.listNoticesWithPagination(current, size);
        int total = noticeService.countNotices();

        // 构造返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", notices);
        result.put("total", total);
        result.put("current", current);
        result.put("size", size);

        Map<String, Object> response = new HashMap<>();
        response.put("data", result);
        response.put("success", true);

        return response;
    }


    @GetMapping("/{id}")
    public Notice getNotice(@PathVariable Long id) {
        return noticeService.getNoticeById(id);
    }

    @PostMapping("/add")
    public boolean addNotice(@RequestBody Notice notice) {
        // 如果前端没有设置发布时间，则使用当前时间
        if (notice.getPublishTime() == null) {
            notice.setPublishTime(new Date());
        }
        // 设置创建时间和更新时间
        Date now = new Date();
        notice.setCreateTime(now);
        notice.setUpdateTime(now);
        return noticeService.addNotice(notice);
    }





    @PutMapping("/update")
    public boolean updateNotice(@RequestBody Notice notice) {
        return noticeService.updateNotice(notice);
    }

    @DeleteMapping("/delete/{id}")
    public boolean deleteNotice(@PathVariable Long id) {
        try {
            return noticeService.deleteNotice(id);
        } catch (Exception e) {
            e.printStackTrace(); // 添加日志以便调试
            return false;
        }
    }

    @GetMapping("/top")
    public List<Notice> listTopNotices() {
        return noticeService.listTopNotices();
    }
}
